<template>
  <div id="panel">
    <!-- 查询表单区域 -->
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
        label-width="100px"
        class="query-form-container"
      >
        <el-form-item label="事件名称" prop="eventName">
          <el-select
            v-model="queryParams.eventName"
            placeholder="请选择事件名称"
            style="width: 200px"
          >
            <el-option
              label="2024年12月11日汤营超桥"
              value="20241211tycq"
            ></el-option>
            <el-option
              label="2024年12月15日某河道治理"
              value="20241215hdzl"
            ></el-option>
            <el-option
              label="2024年12月20日水质监测项目"
              value="20241220szjc"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="监测编号" prop="monitorNo">
          <el-input
            v-model="queryParams.monitorNo"
            placeholder="请输入监测编号"
            style="width: 180px"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="监测点名称" prop="monitorPointName">
          <el-input
            v-model="queryParams.monitorPointName"
            placeholder="请输入监测点名称"
            style="width: 180px"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="监测点类型" prop="monitorPointType">
          <el-select
            v-model="queryParams.monitorPointType"
            placeholder="请选择监测点类型"
            style="width: 150px"
          >
            <el-option label="水监测" value="water"></el-option>
            <el-option label="气监测" value="air"></el-option>
            <el-option label="土壤监测" value="soil"></el-option>
            <el-option label="噪声监测" value="noise"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
            size="mini"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh-right"
            @click="resetQuery"
            size="mini"
            style="margin-left: 8px"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格操作区域和列表 -->
    <el-card class="pageContent">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleUpdate"
            :disabled="selectedRows.length !== 1"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleDelete"
            :disabled="selectedRows.length === 0"
            >删除</el-button
          >
        </el-col>
      </el-row>

      <el-table
        :data="tableData"
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        border
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 600 }"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column
          prop="eventName"
          label="事件名称"
          align="center"
          width="180"
        />
        <el-table-column
          prop="monitorNo"
          label="监测编号"
          align="center"
          width="160"
        />
        <el-table-column
          prop="monitorPointName"
          label="监测点名称"
          align="center"
          width="140"
        />
        <el-table-column
          prop="monitorPointType"
          label="监测点类型"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag :type="getTagType(scope.row.monitorPointType)">
              {{
                scope.row.monitorPointType === "water"
                  ? "水监测"
                  : scope.row.monitorPointType === "air"
                  ? "气监测"
                  : scope.row.monitorPointType === "soil"
                  ? "土壤监测"
                  : "噪声监测"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="longitude"
          label="经度"
          align="center"
          width="140"
        />
        <el-table-column
          prop="latitude"
          label="纬度"
          align="center"
          width="140"
        />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDetail(scope.row)"
              style="color: #409eff"
              >详情</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.row)"
              style="color: #67c23a"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="handleDel(scope.row)"
              style="color: #f56c6c"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
          size="mini"
        />
      </el-pagination>
    </el-card>

    <!-- 添加/修改监测分布弹框（核心调整部分） -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <!-- 第一行：事件名称 + 监测编号 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*事件名称" prop="eventName" required>
              <el-select
                v-model="form.eventName"
                placeholder="请选择事件名称"
                style="width: 100%"
              >
                <el-option
                  label="2024年12月11日汤营超桥"
                  value="20241211tycq"
                ></el-option>
                <el-option
                  label="2024年12月15日某河道治理"
                  value="20241215hdzl"
                ></el-option>
                <el-option
                  label="2024年12月20日水质监测项目"
                  value="20241220szjc"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测编号" prop="monitorNo">
              <el-input
                v-model="form.monitorNo"
                placeholder="请输入监测编号"
                maxlength="30"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：监测点名称 + 监测点类型 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*监测点名称" prop="monitorPointName" required>
              <el-input
                v-model="form.monitorPointName"
                placeholder="请输入监测点名称"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*监测点类型" prop="monitorPointType" required>
              <el-select
                v-model="form.monitorPointType"
                placeholder="请选择监测点类型"
                style="width: 100%"
              >
                <el-option label="水监测" value="water"></el-option>
                <el-option label="气监测" value="air"></el-option>
                <el-option label="土壤监测" value="soil"></el-option>
                <el-option label="噪声监测" value="noise"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：经度 + 纬度（带地图选点按钮） -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input
                v-model="form.longitude"
                placeholder="请点击地图选点选择经纬度"
                readonly
                style="cursor: pointer"
                @click="openMapSelect"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input
                v-model="form.latitude"
                placeholder="请点击地图选点选择经纬度"
                readonly
                style="cursor: pointer"
                @click="openMapSelect"
              ></el-input>
              <el-button
                type="primary"
                size="mini"
                style="margin-top: 8px"
                @click="openMapSelect"
              >
                <i class="el-icon-location"></i> 地图选点
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：备注 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注信息（可选）"
                :rows="3"
                maxlength="200"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 地图选点弹框（模拟） -->
    <el-dialog
      title="地图选点"
      :visible.sync="mapDialogOpen"
      width="800px"
      append-to-body
    >
      <div
        class="map-container"
        style="
          width: 100%;
          height: 400px;
          background: #f5f5f5;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1px solid #eee;
        "
      >
        <span>地图组件占位（实际项目中可集成高德/百度地图 SDK）</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="mapDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="confirmMapPoint">确认选择</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MonitorPointManagement",
  dicts: ["sys_normal_disable"],
  components: {},
  data() {
    return {
      tableHeight: window.innerHeight - 400,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventName: "",
        monitorNo: "",
        monitorPointName: "",
        monitorPointType: "",
      },
      // 表格数据
      tableList: {
        total: 0,
        rows: [],
      },
      selectedRows: [], // 选中的表格数据
      tableData: [
        {
          eventName: "2024年12月11日汤营超桥",
          monitorNo: "af27acdc89",
          monitorPointName: "1#监测点",
          monitorPointType: "water",
          longitude: "111.816095",
          latitude: "33.988902",
          remark: "河道主流监测点",
        },
        {
          eventName: "2024年12月11日汤营超桥",
          monitorNo: "69f9dc6872",
          monitorPointName: "2#监测点",
          monitorPointType: "water",
          longitude: "111.826239",
          latitude: "33.986444",
          remark: "桥下游500米监测点",
        },
        {
          eventName: "2024年12月11日汤营超桥",
          monitorNo: "b39b450836",
          monitorPointName: "3#监测点",
          monitorPointType: "water",
          longitude: "111.836128",
          latitude: "33.989921",
          remark: "桥上游300米监测点",
        },
        {
          eventName: "2024年12月11日汤营超桥",
          monitorNo: "b4ddd31c91",
          monitorPointName: "4#监测点",
          monitorPointType: "air",
          longitude: "111.843550",
          latitude: "33.986794",
          remark: "空气质量监测点",
        },
        {
          eventName: "2024年12月11日汤营超桥",
          monitorNo: "29b407bb55",
          monitorPointName: "5#监测点",
          monitorPointType: "soil",
          longitude: "111.851433",
          latitude: "33.991384",
          remark: "周边土壤监测点",
        },
      ],
      // 弹框控制
      open: false,
      mapDialogOpen: false,
      title: "",
      // 表单数据
      form: {
        eventName: "",
        monitorNo: "",
        monitorPointName: "",
        monitorPointType: "",
        longitude: "",
        latitude: "",
        remark: "",
      },
      // 表单校验规则（匹配必填项）
      rules: {
        eventName: [
          { required: true, message: "请选择事件名称", trigger: "blur" },
        ],
        monitorNo: [
          {
            min: 6,
            max: 30,
            message: "监测编号长度为6-30个字符",
            trigger: "blur",
          },
        ],
        monitorPointName: [
          { required: true, message: "请输入监测点名称", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "监测点名称长度为2-50个字符",
            trigger: "blur",
          },
        ],
        monitorPointType: [
          { required: true, message: "请选择监测点类型", trigger: "blur" },
        ],
        longitude: [
          {
            pattern:
              /^-?((0|1?[0-7]?[0-9]|180)\.\d{0,6}|(0|1?[0-7]?[0-9]|180))$/,
            message: "请输入有效的经度",
            trigger: "blur",
          },
        ],
        latitude: [
          {
            pattern: /^-?((0|[1-8]?[0-9])\.\d{0,6}|(0|[1-8]?[0-9]))$/,
            message: "请输入有效的纬度",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.pageInit();
  },
  methods: {
    // 页面初始化
    pageInit() {
      this.getList();
    },

    // 获取表格数据
    getList() {
      // 实际项目中替换为接口请求
      this.tableData.forEach((item, index) => {
        item.index =
          (this.queryParams.pageNum - 1) * this.queryParams.pageSize +
          index +
          1;
      });
      this.tableList.total = this.tableData.length;
    },

    // 表格选中事件
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 获取标签类型
    getTagType(type) {
      switch (type) {
        case "water":
          return "primary";
        case "air":
          return "success";
        case "soil":
          return "warning";
        case "noise":
          return "info";
        default:
          return "default";
      }
    },

    // 新增按钮操作（核心：打开新增弹框）
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监测分布";
    },

    // 批量修改按钮操作
    handleUpdate() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择一条数据进行修改");
        return;
      }
      if (this.selectedRows.length > 1) {
        this.$message.warning("只能选择一条数据进行修改");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "修改监测分布";
      this.form = { ...this.selectedRows[0] };
    },

    // 批量删除按钮操作
    handleDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择需要删除的数据");
        return;
      }
      this.$confirm(
        "确定要删除选中的 " + this.selectedRows.length + " 条数据吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 实际项目中替换为删除接口
          const monitorNos = this.selectedRows.map((item) => item.monitorNo);
          this.tableData = this.tableData.filter(
            (item) => !monitorNos.includes(item.monitorNo)
          );
          this.tableList.total = this.tableData.length;
          this.selectedRows = [];
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 查看详情
    handleDetail(row) {
      this.$message.info(
        "查看 " + row.monitorPointName + " 详情：" + JSON.stringify(row)
      );
      // 实际项目中可打开详情弹框
    },

    // 单行修改
    handleEdit(row) {
      this.reset();
      this.open = true;
      this.title = "修改监测分布";
      this.form = { ...row };
    },

    // 单行删除
    handleDel(row) {
      this.$confirm("确定要删除 " + row.monitorPointName + " 吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 实际项目中替换为删除接口
          this.tableData = this.tableData.filter(
            (item) => item.monitorNo !== row.monitorNo
          );
          this.tableList.total = this.tableData.length;
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 搜索查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 实际项目中替换为带查询条件的接口请求
      let filteredData = [...this.tableData];
      if (this.queryParams.eventName) {
        filteredData = filteredData.filter(
          (item) => item.eventName === this.queryParams.eventName
        );
      }
      if (this.queryParams.monitorNo) {
        filteredData = filteredData.filter((item) =>
          item.monitorNo.includes(this.queryParams.monitorNo)
        );
      }
      if (this.queryParams.monitorPointName) {
        filteredData = filteredData.filter((item) =>
          item.monitorPointName.includes(this.queryParams.monitorPointName)
        );
      }
      if (this.queryParams.monitorPointType) {
        filteredData = filteredData.filter(
          (item) => item.monitorPointType === this.queryParams.monitorPointType
        );
      }
      this.tableList.total = filteredData.length;
      // 这里仅做前端筛选演示，实际项目中由后端返回筛选结果
    },

    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        eventName: "",
        monitorNo: "",
        monitorPointName: "",
        monitorPointType: "",
      };
      this.getList();
    },

    // 打开地图选点
    openMapSelect() {
      this.mapDialogOpen = true;
      // 实际项目中初始化地图组件（示例：高德地图）
      // initMap()  // 地图初始化方法
    },

    // 确认地图选点
    confirmMapPoint() {
      // 模拟地图选点结果，实际项目中从地图组件获取经纬度
      this.form.longitude = "111.830000";
      this.form.latitude = "33.990000";
      this.mapDialogOpen = false;
      this.$message.success("经纬度选择成功");
    },

    // 取消弹框
    cancel() {
      this.open = false;
      this.mapDialogOpen = false;
      this.reset();
    },

    // 重置表单
    reset() {
      this.form = {
        eventName: "",
        monitorNo: "",
        monitorPointName: "",
        monitorPointType: "",
        longitude: "",
        latitude: "",
        remark: "",
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },

    // 提交表单（新增/修改）
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 新增逻辑：监测编号可选，若填写则校验唯一性
          if (!this.form.monitorNo) {
            // 自动生成监测编号（示例）
            this.form.monitorNo =
              "MON" + new Date().getTime().toString().slice(-8);
          } else {
            // 校验监测编号唯一性（排除当前修改的记录）
            const isDuplicate = this.tableData.some(
              (item) =>
                item.monitorNo === this.form.monitorNo &&
                !(
                  this.selectedRows.length === 1 &&
                  this.selectedRows[0].monitorNo === this.form.monitorNo
                )
            );
            if (isDuplicate) {
              this.$message.error("监测编号已存在，请更换");
              return;
            }
          }

          if (
            this.selectedRows.length === 1 &&
            this.selectedRows[0].monitorNo === this.form.monitorNo
          ) {
            // 修改逻辑
            const index = this.tableData.findIndex(
              (item) => item.monitorNo === this.form.monitorNo
            );
            if (index > -1) {
              this.tableData.splice(index, 1, { ...this.form });
            }
            this.$message.success("修改成功");
          } else {
            // 新增逻辑
            this.tableData.unshift({ ...this.form });
            this.tableList.total = this.tableData.length;
            this.$message.success("新增成功");
          }
          this.open = false;
          this.getList();
        }
      });
    },

    // 导出数据
    handleExport() {
      this.$message.info("导出功能执行中...");
      // 实际项目中替换为导出接口
    },
  },
  watch: {
    // 窗口大小改变时调整表格高度
    "window.innerHeight"(val) {
      this.tableHeight = val - 400;
    },
  },
};
</script>

<style lang="scss" scoped>
#panel {
  padding: 10px;
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;
  background-color: #f9f9f9;

  // 分页样式
  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 14px;
      line-height: 36px;
    }

    .refresh-button {
      position: absolute;
      left: 80px;
      background: transparent;
      border: none;
      color: #409eff;

      &:hover {
        color: #66b1ff;
        background: transparent;
        border: none;
      }

      .el-icon-refresh {
        font-size: 16px;
      }
    }
  }

  // 卡片样式
  .el-card {
    margin: 10px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }

  // 查询表单样式
  .queryForm {
    .el-card__body {
      padding: 15px 20px !important;
    }

    .query-form-container {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    .el-form-item {
      margin-right: 15px;
      margin-bottom: 10px;
    }

    .el-form-item__label {
      color: #333;
      font-weight: 500;
    }
  }

  // 内容区域样式
  .pageContent {
    .mb8 {
      margin-bottom: 10px;
      padding-left: 5px;
    }

    .el-table {
      margin-top: 10px;
      border-radius: 4px;
      overflow: hidden;
    }

    .el-table__row {
      &:hover {
        background-color: #fafafa;
      }
    }

    .el-table-column {
      .cell {
        white-space: nowrap;
      }
    }
  }

  // 弹框表单样式（核心调整）
  .dialog-form {
    .el-form-item {
      margin-bottom: 20px;
    }

    .el-form-item__label {
      color: #333;
      font-weight: 500;
      &::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
      // 非必填项移除*
      &.el-form-item__label--no-asterisk::before {
        content: "";
        margin-right: 0;
      }
    }

    .el-input[readonly] {
      background-color: #f9f9f9;
      color: #666;
    }

    .el-button--primary {
      background-color: #409eff;
      border-color: #409eff;
      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
    }

    .el-textarea {
      width: 100%;
    }
  }

  // 弹框底部样式
  .dialog-footer {
    text-align: right;
    margin-top: 10px;
  }

  // 地图选点弹框样式
  .map-container {
    font-size: 14px;
    color: #666;
  }

  // 响应式调整
  @media (max-width: 1200px) {
    .queryForm .el-form-item {
      margin-right: 10px;
    }
  }

  @media (max-width: 992px) {
    .tableHeight {
      height: auto !important;
    }

    .queryForm .el-form {
      flex-direction: column;
      align-items: flex-start !important;
    }

    .queryForm .el-form-item {
      width: 100%;
      margin-right: 0;
    }

    // 弹框表单自适应
    .dialog-form .el-row {
      flex-direction: column;
    }

    .dialog-form .el-col {
      width: 100% !important;
      margin-bottom: 10px;
    }
  }
}
</style>
